package com.itesm.distribuidos.mexicantrain;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.util.Stack;

public class MexicanTrainClient {
	private InetAddress address;
	private SocketAddress socketAddress;
	private Socket socket;
	private String ip = "10.43.8.80";

    public MexicanTrainClient(MainGUI gui) {
		try { address = InetAddress.getByName(ip); }
		catch (UnknownHostException uhe) { System.out.println("Client - Unknow Host Error"); }
		socketAddress = new InetSocketAddress(address,60000);
		new ServerListener(address,gui).start();
    }

	@SuppressWarnings("unchecked")
	public Stack<Domino> getHand() {
    	return (Stack<Domino>) requestFromServer(0);
    }

	public Domino drawTile() {
    	return (Domino) requestFromServer(1);
    }

    public GameBoard getGameBoard() {
    	return (GameBoard) requestFromServer(2);
    }

    public int getMyTurn() {
    	return (Integer) requestFromServer(3);
    }

    public void setTileOnBoard(Domino tile, int player) {
    	tile.setUser(player);
    	sendToServer(tile);
    }

    public Object requestFromServer(int operation) {
    	Object data;
    	try {
    		socket = new Socket();
    		socket.connect(socketAddress);
    		ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
    		oos.flush();
			oos.writeObject(operation);
		    ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
		    data = ois.readObject();
		    oos.close();
		    ois.close();
			socket.close();
			return data;
		}
		catch (IOException ioe) { System.out.println("Client - IO Error @requestFromServer - operation " + operation); }
		catch (ClassNotFoundException cnfe) { System.out.println("Client - Class Not Found Error @requestFromServer - operation " + operation); }
    	return null;
    }

    public void sendToServer(Object data) {
		try {
    		socket = new Socket();
    		socket.connect(socketAddress);
    		ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
    		oos.flush();
    		if (data instanceof Integer) { oos.writeObject((Integer) data); }
    		if (data instanceof Domino)  { oos.writeObject((Domino) data);  }
		    oos.close();
			socket.close();
		}
		catch (IOException ioe) { System.out.println("Client - IO Error @sendToServer"); }
    }
}
